import Api from "../../utils/api"
import Config from "../../utils/Config"
Page({
  data:{
    page:1, //页数
    recipes:[],
    title:'',
    tip:false,
    tips:false
  },
  onLoad(options){
    let {id,title,tag} = options;
    this.data.tag = tag;
    this.data.id = id;
    this.data.title = title;
    // console.log(id,title,tag);
    wx.setNavigationBarTitle({
      title: title,
    })
    this._getRecipeList()
  },
  // 获取菜谱分类
  async _getRecipeList(){
    let tag = this.data.tag;
    let title = this.data.title
    let where = {},orderBy={field:"_id",sort:"asc"}
    console.log(tag);
    if(tag=="ptfl"){
     where = {
        status:1,
        recipeTypeid:this.data.id
      }
    }else if(tag=="tjcp"){
      where = {
        status:1
      }
      orderBy ={  
          field:"follows",
          sort:"desc",
      }
    }else if(tag == "rmcp"){
      where = {
        status:1
      }
      orderBy ={
          field:"views",
          sort:"desc",
      }
    }else{
      let title = this.data.title
      console.log(title);
      
      where = {
        status:1,
        // 模糊匹配
        recipesName:Api.db.RegExp({
          regexp: title,
          options: 'i',
        })
      }
    }
    let res = await Api.find(Config.tables.recipesTable,where,5,this.data.page,orderBy)
    if(res.data.length <= 0&&res.data.page==1){
      this.setData({
        tip:true
      })
    }
    if(res.data.length <= 5&&res.data.page!=1){
      this.setData({
        tips:true
      })
    }
    // 获取用户信息
    let allPrmoise = []
    res.data.forEach((item)=>{
      // 通过菜谱的openid去查询用户
      let promise = Api.find(Config.tables.userTable,{_openid:item._openid})
      allPrmoise.push(promise)
    }) 
    let alluser = await Promise.all(allPrmoise)
    // console.log(alluser);
    // 遍历拿取到每一个发布者的信息
    res.data.forEach((item,index)=>{
      return item.userinfo = alluser[index].data[0].userinfo
    })
    // console.log(res);
    // 数据拼接
    res.data = this.data.recipes.concat(res.data) 
    this.setData({
      recipes:res.data
    })
  },
  onReachBottom(){
    // 上拉触底
    this.data.page++
    this._getRecipeList();
  },
     // 跳转到详情页面
     getRecipeDetal(e){ 
      console.log(1);
      // 将数据获取出来后进行页面跳转
      let {id,recipesname} = e.currentTarget.dataset
      wx.navigateTo({
        url: `../recipeDetail/recipeDetail?id=${id}&recipesname=${recipesname}`,
      })
    },
})